package admin_user_api

import (
	"blog_go/global"
	"blog_go/models"
	"blog_go/models/ctype"
	"blog_go/models/res"
	"blog_go/plugins/log_stash"
	"blog_go/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"github.com/sirupsen/logrus"
)

type EmailLoginReq struct {
	UserName string `json:"user_name" binding:"required" msg:"用户名必填"`
	Pwd      string `json:"pwd"  binding:"required" msg:"密码必填"`
}
type EmailLoginRsp struct {
	Token string `json:"token"`
}

func (AdminUserApi) EmailLogin(c *gin.Context) {
	var req EmailLoginReq
	if err := c.ShouldBind(&req); err != nil {
		// 没找到
		logrus.Error(err)
		panic(err)
	}
	behaviorLog := log_stash.NewBLogByGin(c)
	var userModel models.UserModel
	err := global.DB.Take(&userModel, "user_name = ? or email = ?", req.UserName, req.UserName).Error
	if err != nil {
		logrus.Warn(err)
		behaviorLog.Warn(fmt.Sprintf("%s 用户名不存在", req.UserName))
		panic(err)
	}
	// 校验密码
	if !utils.ComparePwd(userModel.Password, req.Pwd) {
		logrus.Warn("密码不正确")
		behaviorLog.Warn(fmt.Sprintf("用户名密码错误 %s %s", req.UserName, req.Pwd))
		panic(errors.New("密码不正确"))
	}
	// 登录成功生成token
	tokenString, err := utils.GetToken(utils.JwtPayLoad{
		NickName: userModel.NickName,
		Avatar:   userModel.Avatar,
		Role:     int(userModel.Role),
		UserID:   userModel.ID,
	})
	if err != nil {
		logrus.Error("生成token错误", err)
		behaviorLog.Error(fmt.Sprintf("生成token错误 %s", err))
		panic(err)
	}
	behaviorLog.Info(fmt.Sprintf("%s 登录成功", req.UserName))
	ip, addr := utils.GetAddrByGin(c)
	global.DB.Create(&models.LoginDataModel{
		UserID:    userModel.ID,
		IP:        ip,
		NickName:  userModel.NickName,
		Token:     tokenString,
		Device:    "",
		Addr:      addr,
		LoginType: ctype.SignEmail,
	})
	// token添加到redis
	var jwtInfo utils.JwtPayLoad
	copier.Copy(&jwtInfo, &userModel)
	utils.SetTokenRedis(tokenString, jwtInfo)
	res.OkWithDate(EmailLoginRsp{Token: tokenString}, c)
}
